import { LOGIN_PAGE } from "./../enums/routerEnum";
import { Tips } from "./const";
import { Toast } from "./uniHooks/toast";
import { assign } from "lodash-es";
import { TOKEN } from "./auth";
import {
	useAuthStore
} from '@/store/modules/auth';
import { jumpLogin } from "./routerInterceptor";
let url: string;

if (process.env.NODE_ENV === "development") {
	//  192.168.2.4 测试地址
	// url = "http://222.174.234.90:8885/yxerp"

	//  本地测试地址
	//  url = "http://192.168.2.81:8885/yxerp"
	
	//  服务器正式地址
	url = "http://www.xt-xcl.com:9997/yxerp";
} else {
	//  192.168.2.4 测试地址
	// url = "http://222.174.234.90:8885/yxerp"

	//  本地测试地址
	//  url = "http://192.168.2.81:8885/yxerp"
	
	//  服务器正式地址
	url = "http://www.xt-xcl.com:9997/yxerp";
}
export const baseUrl = url;
function request(
	params: UniNamespace.RequestOptions | string,
	requestOptions?: Partial<UniNamespace.RequestOptions>
) {
	return new Promise((resolve, reject) => {
		if (typeof params === "string") {
			//兼容todolist apihooks文件里面的接口
			return uni.request({
				url: params,
				header: assign(requestOptions?.header, {
					Authorization: TOKEN() || "",
				}),
				success: (res: AnyObject) => {
					//返回数据及处理

					if (res.statusCode == 200) {
						return resolve(res.data);
					}
					resolve(res);
				},
				fail: (err) => {
					reject(err);
				},
				...requestOptions,
			});
		} else {
			return uni.request({
				...params,
				header: assign(params?.header, {
					Authorization: TOKEN() || "",
				}),
				success: (res: AnyObject) => {
					//返回数据及处理
					if (res.statusCode == 200) {
						return resolve(res.data);
					}
					resolve(res);
				},
				fail: (err) => {
					reject(err);
				},
			});
		}
	});
}

let temp;
uni.addInterceptor("request", {
	invoke(args) {
		// request 触发前拼接 url
		args.url = baseUrl + args.url;
	},
	success(args) {
		if (temp) clearTimeout(temp);
		if (args?.data?.code !== '0' || args?.data?.tokenExpire === '1') {
			temp = setTimeout(() => {
				uni.showToast({
					icon:'error',
					title:args?.data?.msg
				})
				if(args?.data?.code === '401' || args?.data?.tokenExpire === '1'){
					useAuthStore().setOrcancelPollingInterval()
				}
				if(args?.data?.tokenExpire === '1'){
					jumpLogin(true);
				}
			}, 800);
		}
		return args;
	},
	fail(err) {


	},
	complete(res) {
		uni.hideLoading();
		uni.stopPullDownRefresh();
		// console.log("interceptor-complete", res);
	},
});

export default request;
